package servlet;

import DBTool.DB;
import Dao.brandDao;
import Dao.selectDao;
import bean.Brand;
import bean.Car;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.SimpleFormatter;

@WebServlet("/car/*")
public class CarSer extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html");
        String path = req.getPathInfo();
        if (path == null || path.equals("/")) {
            ArrayList<Car> list = new selectDao().getAllcar();
            req.setAttribute("list", list);
            req.getRequestDispatcher("/WEB-INF/getlist.jsp").forward(req, resp);
        } else if (path.equals("/add")) {
            ArrayList<Brand> list = new brandDao().getbrand();
            req.setAttribute("list", list);
            req.getRequestDispatcher("/WEB-INF/add.jsp").forward(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html");
        String path = req.getPathInfo();
        if (path.equals("/save")) {
            String name = req.getParameter("name");
            String brandid = req.getParameter("brandid");
            String content = req.getParameter("content");
            int price = Integer.parseInt(req.getParameter("price"));
            String date = req.getParameter("date");
            SimpleDateFormat da = new SimpleDateFormat("yyyy-MM-dd");
            Date newdate = null;
            try {
                newdate = da.parse(date);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }

            Car car = new Car(0, null, name, content, price, newdate);
            selectDao selectDao = new selectDao();
            int i = selectDao.add(car);
            System.out.println(i);
            if (i > 0) {
                resp.sendRedirect("/car");
            }
        }
    }
}
